home *** CD-ROM | disk | FTP | other *** search
/ Exame Informatica 139 / Exame Informatica 139.iso / Revista / Flash / Uniform Server / diskw / home / admin / www / phpMyAdmin / sql.php < prev    next >
Encoding:
PHP Script  |  2005-08-11  |  38.9 KB  |  934 lines

  1. <?php
  2. /* $Id: sql.php,v 2.53 2005/08/12 01:06:18 lem9 Exp $ */
  3. // vim: expandtab sw=4 ts=4 sts=4:
  4.  
  5. /**
  6.  * Gets some core libraries
  7.  */
  8. require_once('./libraries/grab_globals.lib.php');
  9. require_once('./libraries/common.lib.php');
  10. require_once('./libraries/tbl_indexes.lib.php');
  11.  
  12. /**
  13.  * Defines the url to return to in case of error in a sql statement
  14.  */
  15. // Security checkings
  16. if (!empty($goto)) {
  17.     $is_gotofile     = preg_replace('@^([^?]+).*$@s', '\\1', $goto);
  18.     if (!@file_exists('./' . $is_gotofile)) {
  19.         unset($goto);
  20.     } else {
  21.         $is_gotofile = ($is_gotofile == $goto);
  22.     }
  23. } // end if (security checkings)
  24.  
  25. if (empty($goto)) {
  26.     $goto         = (empty($table)) ? $cfg['DefaultTabDatabase'] : $cfg['DefaultTabTable'];
  27.     $is_gotofile  = TRUE;
  28. } // end if
  29. if (!isset($err_url)) {
  30.     $err_url = (!empty($back) ? $back : $goto)
  31.              . '?' . PMA_generate_common_url(isset($db) ? $db : '')
  32.              . ((strpos(' ' . $goto, 'db_details') != 1 && isset($table)) ? '&table=' . urlencode($table) : '');
  33. } // end if
  34.  
  35. // Coming from a bookmark dialog
  36. if (isset($fields['query'])) {
  37.     $sql_query = $fields['query'];
  38. }
  39.  
  40. // This one is just to fill $db
  41. if (isset($fields['dbase'])) {
  42.     $db = $fields['dbase'];
  43. }
  44.  
  45. // Now we can check the parameters
  46. PMA_checkParameters(array('sql_query', 'db'));
  47.  
  48. // instead of doing the test twice
  49. $is_drop_database = preg_match('@DROP[[:space:]]+DATABASE[[:space:]]+@i', $sql_query);
  50.  
  51. /**
  52.  * Check rights in case of DROP DATABASE
  53.  *
  54.  * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
  55.  * but since a malicious user may pass this variable by url/form, we don't take
  56.  * into account this case.
  57.  */
  58. if (!defined('PMA_CHK_DROP')
  59.     && !$cfg['AllowUserDropDatabase']
  60.     && $is_drop_database) {
  61.     // Checks if the user is a Superuser
  62.     // TODO: set a global variable with this information
  63.     // loic1: optimized query
  64.     if (!($result = PMA_DBI_select_db('mysql'))) {
  65.         require_once('./header.inc.php');
  66.         PMA_mysqlDie($strNoDropDatabases, '', '', $err_url);
  67.     } // end if
  68. } // end if
  69.  
  70.  
  71. /**
  72.  * Need to find the real end of rows?
  73.  */
  74.  
  75. if (isset($find_real_end) && $find_real_end) {
  76.     $unlim_num_rows = PMA_countRecords($db, $table, TRUE, TRUE);
  77.     $pos = @((ceil($unlim_num_rows / $session_max_rows) - 1) * $session_max_rows);
  78. }
  79.  
  80. /**
  81.  * Bookmark add
  82.  */
  83. if (isset($store_bkm)) {
  84.     require_once('./libraries/bookmark.lib.php');
  85.     PMA_addBookmarks($fields, $cfg['Bookmark'], (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false));
  86.     PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . $goto);
  87. } // end if
  88.  
  89.  
  90. /**
  91.  * Gets the true sql query
  92.  */
  93. // $sql_query has been urlencoded in the confirmation form for drop/delete
  94. // queries or in the navigation bar for browsing among records
  95. if (isset($btnDrop) || isset($navig)) {
  96.     $sql_query = urldecode($sql_query);
  97. }
  98.  
  99. /**
  100.  * Reformat the query
  101.  */
  102.  
  103. $GLOBALS['unparsed_sql'] = $sql_query;
  104. $parsed_sql = PMA_SQP_parse($sql_query);
  105. $analyzed_sql = PMA_SQP_analyze($parsed_sql);
  106. // Bug #641765 - Robbat2 - 12 January 2003, 10:49PM
  107. // Reverted - Robbat2 - 13 January 2003, 2:40PM
  108.  
  109. // lem9: for bug 780516: now that we use case insensitive preg_match
  110. // or flags from the analyser, do not put back the reformatted query
  111. // into $sql_query, to make this kind of query work without
  112. // capitalizing keywords:
  113. //
  114. // CREATE TABLE SG_Persons (
  115. //  id int(10) unsigned NOT NULL auto_increment,
  116. //  first varchar(64) NOT NULL default '',
  117. //  PRIMARY KEY  (`id`)
  118. // )
  119. //
  120. // Note: now we probably do not need to fill and use $GLOBALS['unparsed_sql']
  121. // but I let this intact for now.
  122. //
  123. //$sql_query = PMA_SQP_formatHtml($parsed_sql, 'query_only');
  124.  
  125.  
  126. // check for a real SELECT ... FROM
  127. $is_select = isset($analyzed_sql[0]['queryflags']['select_from']);
  128.  
  129. // If the query is a Select, extract the db and table names and modify
  130. // $db and $table, to have correct page headers, links and left frame.
  131. // db and table name may be enclosed with backquotes, db is optionnal,
  132. // query may contain aliases.
  133.  
  134. // (TODO: if there are more than one table name in the Select:
  135. // - do not extract the first table name
  136. // - do not show a table name in the page header
  137. // - do not display the sub-pages links)
  138.  
  139. if ($is_select) {
  140.     $prev_db = $db;
  141.     if (isset($analyzed_sql[0]['table_ref'][0]['table_true_name'])) {
  142.         $table = $analyzed_sql[0]['table_ref'][0]['table_true_name'];
  143.     }
  144.     if (isset($analyzed_sql[0]['table_ref'][0]['db'])
  145.        && !empty($analyzed_sql[0]['table_ref'][0]['db'])) {
  146.         $db    = $analyzed_sql[0]['table_ref'][0]['db'];
  147.     }
  148.     else {
  149.         $db = $prev_db;
  150.     }
  151.     // Nijel don't change reload, if we already decided to reload in read_dump
  152.     if (!isset($reload) || $reload == 0) {
  153.         $reload  = ($db == $prev_db) ? 0 : 1;
  154.     }
  155. }
  156.  
  157. /**
  158.  * Sets or modifies the $goto variable if required
  159.  */
  160. if ($goto == 'sql.php') {
  161.     $is_gotofile = FALSE;
  162.     $goto = 'sql.php?'
  163.           . PMA_generate_common_url($db, $table)
  164.           . '&pos=' . $pos
  165.           . '&sql_query=' . urlencode($sql_query);
  166. } // end if
  167.  
  168.  
  169. /**
  170.  * Go back to further page if table should not be dropped
  171.  */
  172. if (isset($btnDrop) && $btnDrop == $strNo) {
  173.     if (!empty($back)) {
  174.         $goto = $back;
  175.     }
  176.     if ($is_gotofile) {
  177.         if (strpos(' ' . $goto, 'db_details') == 1 && !empty($table)) {
  178.             unset($table);
  179.         }
  180.         $active_page = $goto;
  181.         require('./' . PMA_securePath($goto));
  182.     } else {
  183.         PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&', '&', $goto));
  184.     }
  185.     exit();
  186. } // end if
  187.  
  188.  
  189. /**
  190.  * Displays the confirm page if required
  191.  *
  192.  * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
  193.  * with js) because possible security issue is not so important here: at most,
  194.  * the confirm message isn't displayed.
  195.  *
  196.  * Also bypassed if only showing php code.or validating a SQL query
  197.  */
  198. if (!$cfg['Confirm']
  199.     || (isset($is_js_confirmed) && $is_js_confirmed)
  200.     || isset($btnDrop)
  201.  
  202.     // if we are coming from a "Create PHP code" or a "Without PHP Code"
  203.     // dialog, we won't execute the query anyway, so don't confirm
  204.     //|| !empty($GLOBALS['show_as_php'])
  205.     || isset($GLOBALS['show_as_php'])
  206.  
  207.     || !empty($GLOBALS['validatequery'])) {
  208.     $do_confirm = FALSE;
  209. } else {
  210.     $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
  211. }
  212.  
  213. if ($do_confirm) {
  214.     $stripped_sql_query = $sql_query;
  215.     require_once('./header.inc.php');
  216.     echo '<table border="0" cellpadding="3" cellspacing="0">' . "\n";
  217.     if ($is_drop_database) {
  218.         echo '    <tr>' . "\n"
  219.            . '        <td class="tblHeadError">' . "\n";
  220.         if($cfg['ErrorIconic']){
  221.             echo '        <img src="' .$pmaThemeImage .'s_warn.png" border="0" hspace="2" vspace="2" align="left" />';
  222.         }
  223.         echo $strDropDatabaseStrongWarning . ' <br />' . "\n";
  224.     } else {
  225.         echo '    <tr>' . "\n"
  226.            . '        <td class="tblHeadError">' . "\n";
  227.         if($cfg['ErrorIconic']){
  228.             echo '        <img src="' .$pmaThemeImage .'s_really.png" border="0" hspace="2" align="middle" />';
  229.         }
  230.     }
  231.     echo $strDoYouReally . "\n"
  232.        . '        </td>' . "\n"
  233.        . '    </tr>' . "\n"
  234.        . '    <tr>' . "\n"
  235.        . '        <td class="tblError">' . "\n"
  236.        . '            <tt>' . htmlspecialchars($stripped_sql_query) . '</tt> ?<br/>' . "\n"
  237.        . '        </td>' . "\n"
  238.        . '    </tr>' . "\n"
  239.        . '    <form action="sql.php" method="post">' . "\n"
  240.        . '    <tr>' . "\n"
  241.        . '        <td align="right">' . "\n"
  242.     ?>
  243.     <?php echo PMA_generate_common_hidden_inputs($db, (isset($table)?$table:'')); ?>
  244.     <input type="hidden" name="sql_query" value="<?php echo urlencode($sql_query); ?>" />
  245.     <input type="hidden" name="zero_rows" value="<?php echo isset($zero_rows) ? PMA_sanitize($zero_rows) : ''; ?>" />
  246.     <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
  247.     <input type="hidden" name="back" value="<?php echo isset($back) ? PMA_sanitize($back) : ''; ?>" />
  248.     <input type="hidden" name="reload" value="<?php echo isset($reload) ? PMA_sanitize($reload) : 0; ?>" />
  249.     <input type="hidden" name="purge" value="<?php echo isset($purge) ? PMA_sanitize($purge) : ''; ?>" />
  250.     <input type="hidden" name="cpurge" value="<?php echo isset($cpurge) ? PMA_sanitize($cpurge) : ''; ?>" />
  251.     <input type="hidden" name="purgekey" value="<?php echo isset($purgekey) ? PMA_sanitize($purgekey) : ''; ?>" />
  252.     <input type="hidden" name="show_query" value="<?php echo isset($show_query) ? PMA_sanitize($show_query) : ''; ?>" />
  253.     <input type="submit" name="btnDrop" value="<?php echo $strYes; ?>" id="buttonYes" />
  254.     <input type="submit" name="btnDrop" value="<?php echo $strNo; ?>" id="buttonNo" />
  255.     <?php
  256.     echo '        </td>' . "\n"
  257.        . '    </tr>' . "\n"
  258.        . '    </form>' . "\n"
  259.        . '</table>';
  260.     echo "\n";
  261. } // end if
  262.  
  263.  
  264. /**
  265.  * Executes the query and displays results
  266.  */
  267. else {
  268.     if (!isset($sql_query)) {
  269.         $sql_query = '';
  270.     }
  271.     // Defines some variables
  272.     // A table has to be created or renamed -> left frame should be reloaded
  273.     // TODO: use the parser/analyzer
  274.  
  275.     if ((!isset($reload) || $reload == 0)
  276.         && (preg_match('@^CREATE TABLE[[:space:]]+(.*)@i', $sql_query)
  277.          || preg_match('@^ALTER TABLE[[:space:]]+(.*)RENAME@i', $sql_query)
  278.          || preg_match('@^TRUNCATE@i', $sql_query))) {
  279.         $reload           = 1;
  280.     }
  281.     // Gets the number of rows per page
  282.     if (empty($session_max_rows)) {
  283.         $session_max_rows = $cfg['MaxRows'];
  284.     } else if ($session_max_rows != 'all') {
  285.         $cfg['MaxRows']   = $session_max_rows;
  286.     }
  287.     // Defines the display mode (horizontal/vertical) and header "frequency"
  288.     if (empty($disp_direction)) {
  289.         $disp_direction   = $cfg['DefaultDisplay'];
  290.     }
  291.     if (empty($repeat_cells)) {
  292.         $repeat_cells     = $cfg['RepeatCells'];
  293.     }
  294.  
  295.     // SK -- Patch: $is_group added for use in calculation of total number of
  296.     //              rows.
  297.     //              $is_count is changed for more correct "LIMIT" clause
  298.     //              appending in queries like
  299.     //                "SELECT COUNT(...) FROM ... GROUP BY ..."
  300.  
  301.     // TODO: detect all this with the parser, to avoid problems finding
  302.     // those strings in comments or backquoted identifiers
  303.  
  304.     $is_explain = $is_count = $is_export = $is_delete = $is_insert = $is_affected = $is_show = $is_maint = $is_analyse = $is_group = $is_func = FALSE;
  305.     if ($is_select) { // see line 141
  306.         $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
  307.         $is_func =  !$is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
  308.         $is_count = !$is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
  309.         $is_export   = (preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query));
  310.         $is_analyse  = (preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query));
  311.     } else if (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
  312.         $is_explain  = TRUE;
  313.     } else if (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
  314.         $is_delete   = TRUE;
  315.         $is_affected = TRUE;
  316.     } else if (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
  317.         $is_insert   = TRUE;
  318.         $is_affected = TRUE;
  319.     } else if (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
  320.         $is_affected = TRUE;
  321.     } else if (preg_match('@^SHOW[[:space:]]+@i', $sql_query)) {
  322.         $is_show     = TRUE;
  323.     } else if (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
  324.         $is_maint    = TRUE;
  325.     }
  326.  
  327.     // Do append a "LIMIT" clause?
  328.     if (isset($pos)
  329.         && (!$cfg['ShowAll'] || $session_max_rows != 'all')
  330.         && !($is_count || $is_export || $is_func || $is_analyse)
  331.         && isset($analyzed_sql[0]['queryflags']['select_from'])
  332.         && !isset($analyzed_sql[0]['queryflags']['offset'])
  333.         && !preg_match('@[[:space:]]LIMIT[[:space:]0-9,-]+$@i', $sql_query)) {
  334.         $sql_limit_to_append = " LIMIT $pos, ".$cfg['MaxRows'] . " ";
  335.  
  336. //        if (preg_match('@(.*)([[:space:]](PROCEDURE[[:space:]](.*)|FOR[[:space:]]+UPDATE|LOCK[[:space:]]+IN[[:space:]]+SHARE[[:space:]]+MODE))$@i', $sql_query, $regs)) {
  337. //            $full_sql_query  = $regs[1] . $sql_limit_to_append . $regs[2];
  338. //        } else {
  339. //            $full_sql_query  = $sql_query . $sql_limit_to_append;
  340. //        }
  341.  
  342.         $full_sql_query  = $analyzed_sql[0]['section_before_limit'] . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit']; 
  343.         // FIXME: pretty printing of this modified query
  344.  
  345.         if (isset($display_query)) {
  346. //            if (preg_match('@((.|\n)*)(([[:space:]](PROCEDURE[[:space:]](.*)|FOR[[:space:]]+UPDATE|LOCK[[:space:]]+IN[[:space:]]+SHARE[[:space:]]+MODE))|;)[[:space:]]*$@i', $display_query, $regs)) {
  347. //                $display_query  = $regs[1] . $sql_limit_to_append . $regs[3];
  348. //            } else {
  349. //                $display_query  = $display_query . $sql_limit_to_append;
  350. //            }
  351.  
  352.             // if the analysis of the original query revealed that we found 
  353.             // a section_after_limit, we now have to analyze $display_query
  354.             // to display it correctly
  355.  
  356.             if (!empty($analyzed_sql[0]['section_after_limit'])) {
  357.                 $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
  358.                 $display_query  = $analyzed_display_query[0]['section_before_limit'] . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit']; 
  359.             }
  360.         }
  361.  
  362.     } else {
  363.         $full_sql_query      = $sql_query;
  364.     } // end if...else
  365.  
  366.     PMA_DBI_select_db($db);
  367.  
  368.     // If the query is a DELETE query with no WHERE clause, get the number of
  369.     // rows that will be deleted (mysql_affected_rows will always return 0 in
  370.     // this case)
  371.  
  372.     if ($is_delete
  373.         && preg_match('@^DELETE([[:space:]].+)?(FROM[[:space:]](.+))$@i', $sql_query, $parts)
  374.         && !preg_match('@[[:space:]]WHERE[[:space:]]@i', $parts[3])) {
  375.         $cnt_all_result = @PMA_DBI_try_query('SELECT COUNT(*) as count ' .  $parts[2]);
  376.         if ($cnt_all_result) {
  377.             list($num_rows) = PMA_DBI_fetch_row($cnt_all_result);
  378.             PMA_DBI_free_result($cnt_all_result);
  379.         } else {
  380.             $num_rows   = 0;
  381.         }
  382.     }
  383.  
  384.     //  E x e c u t e    t h e    q u e r y
  385.  
  386.     // Only if we didn't ask to see the php code (mikebeck)
  387.     if (isset($GLOBALS['show_as_php']) || !empty($GLOBALS['validatequery'])) {
  388.         unset($result);
  389.         $num_rows = 0;
  390.     }
  391.     else {
  392.         // garvin: Measure query time. TODO-Item http://sourceforge.net/tracker/index.php?func=detail&aid=571934&group_id=23067&atid=377411
  393.         list($usec, $sec) = explode(' ',microtime());
  394.         $querytime_before = ((float)$usec + (float)$sec);
  395.  
  396.         $result   = @PMA_DBI_try_query($full_sql_query, NULL, PMA_DBI_QUERY_STORE);
  397.  
  398.         list($usec, $sec) = explode(' ',microtime());
  399.         $querytime_after = ((float)$usec + (float)$sec);
  400.  
  401.         $GLOBALS['querytime'] = $querytime_after - $querytime_before;
  402.  
  403.         // Displays an error message if required and stop parsing the script
  404.         if ($error        = PMA_DBI_getError()) {
  405.             require_once('./header.inc.php');
  406.             $full_err_url = (preg_match('@^(db_details|tbl_properties)@', $err_url))
  407.                           ? $err_url . '&show_query=1&sql_query=' . urlencode($sql_query)
  408.                           : $err_url;
  409.             PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
  410.         }
  411.         unset($error);
  412.  
  413.         // Gets the number of rows affected/returned
  414.         // (This must be done immediately after the query because
  415.         // mysql_affected_rows() reports about the last query done)
  416.  
  417.         if (!$is_affected) {
  418.             $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
  419.         } else if (!isset($num_rows)) {
  420.             $num_rows = @PMA_DBI_affected_rows();
  421.         }
  422.  
  423.         // Checks if the current database has changed
  424.         // This could happen if the user sends a query like "USE `database`;"
  425.         $res = PMA_DBI_query('SELECT DATABASE() AS \'db\';');
  426.         $row = PMA_DBI_fetch_row($res);
  427.         if (is_array($row) && isset($row[0]) && (strcasecmp($db,$row[0]) != 0)) {
  428.             $db     = $row[0];
  429.             $reload = 1;
  430.         }
  431.         @PMA_DBI_free_result($res);
  432.         unset($res, $row);
  433.  
  434.         // tmpfile remove after convert encoding appended by Y.Kawada
  435.         if (function_exists('PMA_kanji_file_conv')
  436.             && (isset($textfile) && file_exists($textfile))) {
  437.             unlink($textfile);
  438.         }
  439.  
  440.         // Counts the total number of rows for the same 'SELECT' query without the
  441.         // 'LIMIT' clause that may have been programatically added
  442.  
  443.         if (empty($sql_limit_to_append)) {
  444.             $unlim_num_rows         = $num_rows;
  445.             // if we did not append a limit, set this to get a correct
  446.             // "Showing rows..." message
  447.             $GLOBALS['session_max_rows'] = 'all';
  448.         }
  449.         else if ($is_select) {
  450.  
  451.                 //    c o u n t    q u e r y
  452.  
  453.                 // If we are "just browsing", there is only one table,
  454.                 // and no where clause (or just 'WHERE 1 '),
  455.                 // so we do a quick count (which uses MaxExactCount)
  456.                 // because SQL_CALC_FOUND_ROWS
  457.                 // is not quick on large InnoDB tables
  458.  
  459.                 // but do not count again if we did it previously
  460.                 // due to $find_real_end == TRUE
  461.  
  462.                 if (!$is_group
  463.                  && !isset($analyzed_sql[0]['queryflags']['union'])
  464.                  && !isset($analyzed_sql[0]['table_ref'][1]['table_name'])
  465.                  && (empty($analyzed_sql[0]['where_clause'])
  466.                    || $analyzed_sql[0]['where_clause'] == '1 ')
  467.                  && !isset($find_real_end)
  468.                  ) {
  469.  
  470.                     // "j u s t   b r o w s i n g"
  471.                     $unlim_num_rows = PMA_countRecords($db, $table, TRUE);
  472.  
  473.                 } else { // n o t   " j u s t   b r o w s i n g "
  474.  
  475.                     if (PMA_MYSQL_INT_VERSION < 40000) {
  476.  
  477.                         // detect this case:
  478.                         // SELECT DISTINCT x AS foo, y AS bar FROM sometable
  479.  
  480.                         if (isset($analyzed_sql[0]['queryflags']['distinct'])) {
  481.                             $count_what = 'DISTINCT ';
  482.                             $first_expr = TRUE;
  483.                             foreach($analyzed_sql[0]['select_expr'] as $part) {
  484.                                 $count_what .= (!$first_expr ? ', ' : '') . $part['expr'];
  485.                                 $first_expr = FALSE;
  486.                             }
  487.                          } else {
  488.                              $count_what = '*';
  489.                          }
  490.                         $count_query = 'SELECT COUNT(' . $count_what . ') AS count';
  491.                     }
  492.  
  493.                     // add the remaining of select expression if there is
  494.                     // a GROUP BY or HAVING clause
  495.                     if (PMA_MYSQL_INT_VERSION < 40000
  496.                      && $count_what =='*'
  497.                      && (!empty($analyzed_sql[0]['group_by_clause'])
  498.                         || !empty($analyzed_sql[0]['having_clause']))) {
  499.                         $count_query .= ' ,' . $analyzed_sql[0]['select_expr_clause'];
  500.                     }
  501.  
  502.                     if (PMA_MYSQL_INT_VERSION >= 40000) {
  503.                          // add select expression after the SQL_CALC_FOUND_ROWS
  504.  
  505.                             // for UNION, just adding SQL_CALC_FOUND_ROWS
  506.                             // after the first SELECT works.
  507.  
  508.                             // take the left part, could be:
  509.                             // SELECT
  510.                             // (SELECT
  511.                             $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
  512.                             $count_query .= ' SQL_CALC_FOUND_ROWS ';
  513.                             // add everything that was after the first SELECT
  514.                             $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select']+1);
  515.                     } else { // PMA_MYSQL_INT_VERSION < 40000
  516.  
  517.                         if (!empty($analyzed_sql[0]['from_clause'])) {
  518.                             $count_query .= ' FROM ' . $analyzed_sql[0]['from_clause'];
  519.                         }
  520.                         if (!empty($analyzed_sql[0]['where_clause'])) {
  521.                             $count_query .= ' WHERE ' . $analyzed_sql[0]['where_clause'];
  522.                         }
  523.                         if (!empty($analyzed_sql[0]['group_by_clause'])) {
  524.                             $count_query .= ' GROUP BY ' . $analyzed_sql[0]['group_by_clause'];
  525.                         }
  526.                         if (!empty($analyzed_sql[0]['having_clause'])) {
  527.                             $count_query .= ' HAVING ' . $analyzed_sql[0]['having_clause'];
  528.                         }
  529.                     } // end if
  530.  
  531.                     // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
  532.                     // long delays. Returned count will be complete anyway.
  533.                     // (but a LIMIT would disrupt results in an UNION)
  534.  
  535.                     if (PMA_MYSQL_INT_VERSION >= 40000
  536.                     && !isset($analyzed_sql[0]['queryflags']['union'])) {
  537.                         $count_query .= ' LIMIT 1';
  538.                     }
  539.  
  540.                     // run the count query
  541.  
  542.                     if (PMA_MYSQL_INT_VERSION < 40000) {
  543.                         if ($cnt_all_result = PMA_DBI_try_query($count_query)) {
  544.                             if ($is_group && $count_what == '*') {
  545.                                 $unlim_num_rows = @PMA_DBI_num_rows($cnt_all_result);
  546.                             } else {
  547.                                 $unlim_num_rows = PMA_DBI_fetch_assoc($cnt_all_result);
  548.                                 $unlim_num_rows = $unlim_num_rows['count'];
  549.                             }
  550.                             PMA_DBI_free_result($cnt_all_result);
  551.                         } else {
  552.                             if (PMA_DBI_getError()) {
  553.  
  554.                                 // there are some cases where the generated
  555.                                 // count_query (for MySQL 3) is wrong,
  556.                                 // so we get here.
  557.                                 //TODO: use a big unlimited query to get
  558.                                 // the correct number of rows (depending
  559.                                 // on a config variable?)
  560.                                 $unlim_num_rows = 0;
  561.                             }
  562.                         }
  563.                     } else {
  564.                         PMA_DBI_try_query($count_query);
  565.                         // if (mysql_error()) {
  566.                         // void.
  567.                         // I tried the case
  568.                         // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
  569.                         // UNION (SELECT `User`, `Host`, "%" AS "Db",
  570.                         // `Select_priv`
  571.                         // FROM `user`) ORDER BY `User`, `Host`, `Db`;
  572.                         // and although the generated count_query is wrong
  573.                         // the SELECT FOUND_ROWS() work! (maybe it gets the
  574.                         // count from the latest query that worked)
  575.                         //
  576.                         // another case where the count_query is wrong:
  577.                         // SELECT COUNT( * ), f1 from t1 group by f1
  578.                         // and you click to sort on count( * )
  579.                         // }
  580.                         $cnt_all_result       = PMA_DBI_query('SELECT FOUND_ROWS() as count;');
  581.                         list($unlim_num_rows) = PMA_DBI_fetch_row($cnt_all_result);
  582.                         @PMA_DBI_free_result($cnt_all_result);
  583.                     }
  584.             } // end else "just browsing"
  585.  
  586.         } else { // not $is_select
  587.              $unlim_num_rows         = 0;
  588.         } // end rows total count
  589.  
  590.         // garvin: if a table or database gets dropped, check column comments.
  591.         if (isset($purge) && $purge == '1') {
  592.             require_once('./libraries/relation_cleanup.lib.php');
  593.  
  594.             if (isset($table) && isset($db) && !empty($table) && !empty($db)) {
  595.                 PMA_relationsCleanupTable($db, $table);
  596.             } elseif (isset($db) && !empty($db)) {
  597.                 PMA_relationsCleanupDatabase($db);
  598.             } else {
  599.                 // garvin: VOID. No DB/Table gets deleted.
  600.             } // end if relation-stuff
  601.          } // end if ($purge)
  602.  
  603.         // garvin: If a column gets dropped, do relation magic.
  604.         if (isset($cpurge) && $cpurge == '1' && isset($purgekey)
  605.             && isset($db) && isset($table)
  606.             && !empty($db) && !empty($table) && !empty($purgekey)) {
  607.             require_once('./libraries/relation_cleanup.lib.php');
  608.             PMA_relationsCleanupColumn($db, $table, $purgekey);
  609.  
  610.         } // end if column PMA_* purge
  611.     } // end else "didn't ask to see php code"
  612.  
  613.     // No rows returned -> move back to the calling page
  614.     if ($num_rows < 1 || $is_affected) {
  615.         if ($is_delete) {
  616.             $message = $strDeletedRows . ' ' . $num_rows;
  617.         } else if ($is_insert) {
  618.             $message = $strInsertedRows . ' ' . $num_rows;
  619.             $insert_id = PMA_DBI_insert_id();
  620.             if ($insert_id != 0) {
  621.                 // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
  622.                 $message .= '[br]'.$strInsertedRowId . ' ' . ($insert_id + $num_rows - 1);
  623.             }
  624.         } else if ($is_affected) {
  625.             $message = $strAffectedRows . ' ' . $num_rows;
  626.  
  627.             // Ok, here is an explanation for the !$is_select.
  628.             // The form generated
  629.             // by tbl_query_box.php and db_details.php has many submit buttons
  630.             // on the same form, and some confusion arises from the
  631.             // fact that $zero_rows is sent for every case. 
  632.             // The $zero_rows containing $strSuccess and sent with
  633.             // the form should not have priority over 
  634.             // errors like $strEmptyResultSet
  635.         } else if (!empty($zero_rows) && !$is_select) {
  636.             $message = $zero_rows;
  637.         } else if (!empty($GLOBALS['show_as_php'])) {
  638.             $message = $strPhp;
  639.         } else if (!empty($GLOBALS['validatequery'])) {
  640.             $message = $strValidateSQL;
  641.         } else {
  642.             $message = $strEmptyResultSet;
  643.         }
  644.  
  645.         $message .= ' ' . (isset($GLOBALS['querytime']) ? '(' . sprintf($strQueryTime, $GLOBALS['querytime']) . ')' : '');
  646.  
  647.         if ($is_gotofile) {
  648.             $goto = PMA_securePath($goto);
  649.             // Checks for a valid target script
  650.             if (isset($table) && $table == '') {
  651.                 unset($table);
  652.             }
  653.             if (isset($db) && $db == '') {
  654.                 unset($db);
  655.             }
  656.             $is_db = $is_table = FALSE;
  657.             if (strpos(' ' . $goto, 'tbl_properties') == 1) {
  658.                 if (!isset($table)) {
  659.                     $goto     = 'db_details.php';
  660.                 } else {
  661.                     $is_table = @PMA_DBI_query('SHOW TABLES LIKE \'' . PMA_sqlAddslashes($table, TRUE) . '\';', NULL, PMA_DBI_QUERY_STORE);
  662.                     if (!($is_table && @PMA_DBI_num_rows($is_table))) {
  663.                         $goto = 'db_details.php';
  664.                         unset($table);
  665.                     }
  666.                     @PMA_DBI_free_result($is_table);
  667.                 } // end if... else...
  668.             }
  669.             if (strpos(' ' . $goto, 'db_details') == 1) {
  670.                 if (isset($table)) {
  671.                     unset($table);
  672.                 }
  673.                 if (!isset($db)) {
  674.                     $goto     = 'main.php';
  675.                 } else {
  676.                     $is_db    = @PMA_DBI_select_db($db);
  677.                     if (!$is_db) {
  678.                         $goto = 'main.php';
  679.                         unset($db);
  680.                     }
  681.                 } // end if... else...
  682.             }
  683.             // Loads to target script
  684.             if (strpos(' ' . $goto, 'db_details') == 1
  685.                 || strpos(' ' . $goto, 'tbl_properties') == 1) {
  686.                 $js_to_run = 'functions.js';
  687.             }
  688.             if ($goto != 'main.php') {
  689.                 require_once('./header.inc.php');
  690.             }
  691.             $active_page = $goto;
  692.             require('./' . $goto);
  693.         } // end if file_exist
  694.         else {
  695.             PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&', '&', $goto) . '&message=' . urlencode($message));
  696.         } // end else
  697.         exit();
  698.     } // end no rows returned
  699.  
  700.     // At least one row is returned -> displays a table with results
  701.     else {
  702.         // Displays the headers
  703.         if (isset($show_query)) {
  704.             unset($show_query);
  705.         }
  706.         if (isset($printview) && $printview == '1') {
  707.             require_once('./header_printview.inc.php');
  708.         } else {
  709.             $js_to_run = 'functions.js';
  710.             unset($message);
  711.             if (!empty($table)) {
  712.                 require('./tbl_properties_common.php');
  713.                 $url_query .= '&goto=tbl_properties.php&back=tbl_properties.php';
  714.                 require('./tbl_properties_table_info.php');
  715.                 require('./tbl_properties_links.php');
  716.             }
  717.             else {
  718.                 require('./db_details_common.php');
  719.                 require('./db_details_db_info.php');
  720.             }
  721.         }
  722.  
  723.         require_once('./libraries/relation.lib.php');
  724.         $cfgRelation = PMA_getRelationsParam();
  725.  
  726.         // Gets the list of fields properties
  727.         if (isset($result) && $result) {
  728.             $fields_meta = PMA_DBI_get_fields_meta($result);
  729.             $fields_cnt  = count($fields_meta);
  730.         }
  731.  
  732.         // Display previous update query (from tbl_replace)
  733.         if (isset($disp_query) && $cfg['ShowSQL'] == TRUE) {
  734.             $tmp_sql_query = $GLOBALS['sql_query'];
  735.             $GLOBALS['sql_query'] = $disp_query;
  736.             PMA_showMessage($disp_message);
  737.             $GLOBALS['sql_query'] = $tmp_sql_query;
  738.         }
  739.  
  740.         // Displays the results in a table
  741.         require_once('./libraries/display_tbl.lib.php');
  742.         if (empty($disp_mode)) {
  743.             // see the "PMA_setDisplayMode()" function in
  744.             // libraries/display_tbl.lib.php
  745.             $disp_mode = 'urdr111101';
  746.         }
  747.         if (!isset($dontlimitchars)) {
  748.             $dontlimitchars = 0;
  749.         }
  750.  
  751.         PMA_displayTable($result, $disp_mode, $analyzed_sql);
  752.         PMA_DBI_free_result($result);
  753.  
  754.         // BEGIN INDEX CHECK See if indexes should be checked.
  755.         if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
  756.             foreach($selected AS $idx => $tbl_name) {
  757.                 $indexes        = $indexes_info = $indexes_data = array();
  758.                 $tbl_ret_keys   = PMA_get_indexes(urldecode($tbl_name), $err_url_0);
  759.  
  760.                 PMA_extract_indexes($tbl_ret_keys, $indexes, $indexes_info, $indexes_data);
  761.  
  762.                 $idx_collection = PMA_show_indexes(urldecode($tbl_name), $indexes, $indexes_info, $indexes_data, false);
  763.                 $check          = PMA_check_indexes($idx_collection);
  764.                 if (!empty($check)) {
  765.                 ?>
  766. <table border="0" cellpadding="2" cellspacing="0">
  767.     <tr>
  768.         <td class="tblHeaders" colspan="7"><?php printf($strIndexWarningTable, urldecode($tbl_name)); ?></td>
  769.     </tr>
  770.     <?php echo $check; ?>
  771. </table>
  772.                 <?php
  773.                 }
  774.             }
  775.         } // End INDEX CHECK
  776.  
  777.         if ($disp_mode[6] == '1' || $disp_mode[9] == '1') {
  778.             echo "\n";
  779.             echo '<hr />' . "\n";
  780.  
  781.             // Displays "Insert a new row" link if required
  782.             if ($disp_mode[6] == '1') {
  783.                 $lnk_goto  = 'sql.php?'
  784.                            . PMA_generate_common_url($db, $table)
  785.                            . '&pos=' . $pos
  786.                            . '&session_max_rows=' . $session_max_rows
  787.                            . '&disp_direction=' . $disp_direction
  788.                            . '&repeat_cells=' . $repeat_cells
  789.                            . '&dontlimitchars=' . $dontlimitchars
  790.                            . '&sql_query=' . urlencode($sql_query);
  791.                 $url_query = '?'
  792.                            . PMA_generate_common_url($db, $table)
  793.                            . '&pos=' . $pos
  794.                            . '&session_max_rows=' . $session_max_rows
  795.                            . '&disp_direction=' . $disp_direction
  796.                            . '&repeat_cells=' . $repeat_cells
  797.                            . '&dontlimitchars=' . $dontlimitchars
  798.                            . '&sql_query=' . urlencode($sql_query)
  799.                            . '&goto=' . urlencode($lnk_goto);
  800.  
  801.                 echo '    <!-- Insert a new row -->' . "\n";
  802.                 echo PMA_linkOrButton(
  803.                     'tbl_change.php' . $url_query,
  804.                     ($cfg['PropertiesIconic'] ? '<img src="' . $pmaThemeImage . 'b_insrow.png" border="0" height="16" width="16" align="middle" hspace="2" alt="' . $strInsertNewRow . '"/>' : '') . $strInsertNewRow,
  805.                     '', TRUE, TRUE, '') . "\n";
  806.  
  807.                 if ($disp_mode[9] == '1') {
  808.                     echo '  ';
  809.                 }
  810.                 echo "\n";
  811.             } // end insert new row
  812.  
  813.             // Displays "printable view" link if required
  814.             if ($disp_mode[9] == '1') {
  815.                 $url_query = '?'
  816.                            . PMA_generate_common_url($db, $table)
  817.                            . '&pos=' . $pos
  818.                            . '&session_max_rows=' . $session_max_rows
  819.                            . '&disp_direction=' . $disp_direction
  820.                            . '&repeat_cells=' . $repeat_cells
  821.                            . '&printview=1'
  822.                            . '&sql_query=' . urlencode($sql_query);
  823.                 echo '    <!-- Print view -->' . "\n";
  824.                 echo PMA_linkOrButton(
  825.                     'sql.php' . $url_query . ((isset($dontlimitchars) && $dontlimitchars == '1') ? '&dontlimitchars=1' : ''),
  826.                     ($cfg['PropertiesIconic'] ? '<img src="' . $pmaThemeImage . 'b_print.png" border="0" height="16" width="16" align="middle" hspace="2" alt="' . $strPrintView . '"/>' : '') . $strPrintView,
  827.                     '', TRUE, TRUE, 'print_view') . "\n";
  828.  
  829.                 if (!$dontlimitchars) {
  830.                     echo   '      ' . "\n";
  831.                     echo PMA_linkOrButton(
  832.                         'sql.php' . $url_query . '&dontlimitchars=1',
  833.                         ($cfg['PropertiesIconic'] ? '<img src="' . $pmaThemeImage . 'b_print.png" border="0" height="16" width="16" align="middle" hspace="2" alt="' . $strPrintViewFull . '"/>' : '') . $strPrintViewFull,
  834.                         '', TRUE, TRUE, 'print_view') . "\n";
  835.                 }
  836.             } // end displays "printable view"
  837.  
  838.             echo "\n";
  839.         }
  840.  
  841.         // Export link
  842.         // (the url_query has extra parameters that won't be used to export)
  843.         // (the single_table parameter is used in display_export.lib.php
  844.         //  to hide the SQL and the structure export dialogs)
  845.         if (isset($analyzed_sql[0]) && $analyzed_sql[0]['querytype'] == 'SELECT' && !isset($printview)) {
  846.             if (isset($analyzed_sql[0]['table_ref'][0]['table_true_name']) && !isset($analyzed_sql[0]['table_ref'][1]['table_true_name'])) {
  847.                 $single_table   = '&single_table=true';
  848.             } else {
  849.                 $single_table   = '';
  850.             }
  851.             echo '    <!-- Export -->' . "\n";
  852.             echo   '      ' . "\n";
  853.             echo PMA_linkOrButton(
  854.                 'tbl_properties_export.php' . $url_query . '&unlim_num_rows=' . $unlim_num_rows . $single_table,
  855.                 ($cfg['PropertiesIconic'] ? '<img src="' . $pmaThemeImage . 'b_tblexport.png" border="0" height="16" width="16" align="middle" hspace="2" alt="' . $strExport . '" />' : '') . $strExport,
  856.                 '', TRUE, TRUE, '') . "\n";
  857.         }
  858.  
  859.         // Bookmark Support if required
  860.         if ($disp_mode[7] == '1'
  861.             && ($cfg['Bookmark']['db'] && $cfg['Bookmark']['table'] && empty($id_bookmark))
  862.             && !empty($sql_query)) {
  863.             echo "\n";
  864.  
  865.             $goto = 'sql.php?'
  866.                   . PMA_generate_common_url($db, $table)
  867.                   . '&pos=' . $pos
  868.                   . '&session_max_rows=' . $session_max_rows
  869.                   . '&disp_direction=' . $disp_direction
  870.                   . '&repeat_cells=' . $repeat_cells
  871.                   . '&dontlimitchars=' . $dontlimitchars
  872.                   . '&sql_query=' . urlencode($sql_query)
  873.                   . '&id_bookmark=1';
  874.             ?>
  875. <!-- Bookmark the query -->
  876.             <?php
  877.             echo "\n";
  878.             if ($disp_mode[3] == '1') {
  879.                 echo '    <i>' . $strOr . '</i>' . "\n";
  880.             }else echo '<br /><br />';
  881.             ?>
  882. <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
  883. <table border="0" cellpadding="2" cellspacing="0">
  884. <tr><td class="tblHeaders" colspan="2"><?php
  885.      echo ($cfg['PropertiesIconic'] ? '<img src="' . $pmaThemeImage . 'b_bookmark.png" border="0" width="16" height="16" hspace="2" align="middle" alt="' . $strBookmarkThis . '" />' : '')
  886.         . $strBookmarkThis;
  887. ?></td></tr>
  888. <tr bgcolor="<?php echo $cfg['BgcolorOne']; ?>"><td>
  889.     <?php echo $strBookmarkLabel; ?>:
  890.     <?php echo PMA_generate_common_hidden_inputs(); ?>
  891.     <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
  892.     <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
  893.     <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
  894.     <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
  895.         </td><td>
  896.     <input type="text" name="fields[label]" value="" />
  897.         </td></tr>
  898. <tr bgcolor="<?php echo $cfg['BgcolorOne']; ?>"><td align="right" valign="top">
  899.     <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" /></td>
  900.     <td><label for="bkm_all_users"><?php echo $strBookmarkAllUsers; ?></label></td>
  901. </tr>
  902. <tr>
  903.     <td class="tblFooters" colspan="2" align="right">
  904.     <input type="submit" name="store_bkm" value="<?php echo $strBookmarkThis; ?>" />
  905.     </td></tr>
  906. </table></form>
  907.             <?php
  908.         } // end bookmark support
  909.  
  910.         // Do print the page if required
  911.         if (isset($printview) && $printview == '1') {
  912.             echo "\n";
  913.             ?>
  914. <script type="text/javascript" language="javascript1.2">
  915. <!--
  916. // Do print the page
  917. if (typeof(window.print) != 'undefined') {
  918.     window.print();
  919. }
  920. //-->
  921. </script>
  922.             <?php
  923.         } // end print case
  924.     } // end rows returned
  925.  
  926. } // end executes the query
  927. echo "\n\n";
  928.  
  929. /**
  930.  * Displays the footer
  931.  */
  932. require_once('./footer.inc.php');
  933. ?>
  934.